package com.atcumt.Carl.Dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Dfs02 {

    /**
     * 子集
     * 子集问题不需要剪枝！因为子集就是要遍历整棵树
     */
    List<List<Integer>> res = new ArrayList<>(); // 存放符合条件结果的集合
    List<Integer> path = new ArrayList<>(); // 用来存放符合条件结果

    public List<List<Integer>> subsets(int[] nums) {
        subsetsHelper(nums, 0);
        return res;
    }

    private void subsetsHelper(int[] nums, int start) {
        res.add(new ArrayList<>(path));

        for (int i = start; i < nums.length; i++) {
            path.add(nums[i]);
            subsetsHelper(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }

    /**
     * 子集，含有重复元素
     */
    boolean[] used;

    public List<List<Integer>> subsetsWithDup(int[] nums) {

        Arrays.sort(nums);
        used = new boolean[nums.length];
        subsetsWithDupHelper(nums, 0);
        return res;
    }

    private void subsetsWithDupHelper(int[] nums, int start) {
        res.add(new ArrayList<>(path));

        for (int i = start; i < nums.length; i++) {
            if (i > 0 && !used[i - 1] && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true; // 做出选择
            subsetsWithDupHelper(nums, i + 1);
            path.remove(path.size() - 1);
            used[i] = false; // 撤销选择

        }
    }

    /**
     * 全排列:不含重复元素
     */
    public List<List<Integer>> permute(int[] nums) {

        used = new boolean[nums.length];
        premuteHelper(nums);
        return res;
    }

    private void premuteHelper(int[] nums) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            premuteHelper(nums);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }

    /**
     * 全排列：含重复元素
     */
    public List<List<Integer>> permuteUnique(int[] nums) {

        used = new boolean[nums.length];
        Arrays.sort(nums);
        premuteUniqueHelper(nums);
        return res;
    }

    private void premuteUniqueHelper(int[] nums) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }

            if (i > 0 && !used[i - 1] && nums[i] == nums[i - 1]) {
                continue; // 剪枝
            }
            path.add(nums[i]);
            used[i] = true;
            premuteUniqueHelper(nums);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}
